home *** CD-ROM | disk | FTP | other *** search
- /***
- ***
- *** To send data between stream sockets (having communication style
- *** SOCK_STREAM)
- *** Code based on an example taken from SUN® Network Programming Guide,
- *** chapter 10, A Socket-Based Interprocess Communications Tutorial,
- *** Revision A, of 27 March 1990, Fig. 10-11, pp. 270-271.
- ***
- ***/
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <sys/time.h>
- #include <netinet/in.h>
- #include <netdb.h>
- #include <stdio.h>
- #define TRUE (1)
- #define DATA "\nFrom: server\nTo: client\nMssg: Hello client!\n"
- #define Port (31768)
-
- main()
- {
- int sock, length;
- struct sockaddr_in server;
- int msgsock;
- char buf[1024];
- fd_set ready;
- struct timeval to;
-
- /* Create socket. */
- sock = socket(AF_INET, SOCK_STREAM, 0);
- if (sock < 0)
- {
- perror("Server--> opening stream socket");
- exit(1);
- }
- /* Name socket using wildcards. */
- server.sin_family = AF_INET;
- server.sin_addr.s_addr = INADDR_ANY;
- server.sin_port = Port;
- if (bind(sock, (struct sockadd *)&server, sizeof server) < 0)
- {
- perror("Server--> getting socket name");
- exit(1);
- }
- printf("Server--> Socket port #%d\n", ntohs(server.sin_port));
-
- /* Start accepting connections. */
- listen(sock, 5);
- do
- {
- FD_ZERO(&ready);
- FD_SET(sock, &ready);
- to.tv_sec = 5;
- if (select(sock + 1, &ready, (fd_set *)0, (fd_set *)0, &to) < 0)
- {
- perror("Server--> select");
- continue;
- }
- if (FD_ISSET(sock, &ready))
- {
- msgsock = accept(sock, (struct sockaddr *) 0, (int *) 0);
- if (msgsock == -1)
- {
- perror("Server--> accept");
- }
- else
- {
- bzero(buf, sizeof buf);
- if ((length = recv(msgsock, buf, 1024, 0)) < 0)
- {
- perror("Server--> reading stream message");
- }
- else
- {
- buf[length] = '\0';
- printf("Server-->%s\n", buf);
- }
- if (send(msgsock, DATA, sizeof DATA, 0) < 0)
- {
- perror("Server--> sending steam message");
- }
- }
- close(msgsock);
- }
- else
- {
- /* Do something else. */
- }
- } while (TRUE);
- exit(0);
- }
-